package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;

    private static String KEY_PREFIX = "ly:user:phone:";
    @Override
    public Boolean exsit(String data, Integer type) {
        if (type !=1 && type !=2){
             throw new LyException(400,"请求参数不存在");
        }

        return query()
                .eq(type==1,"username",data)
                .eq(type==2,"password",data)
                .count()==1;
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Override
    public void register(User user, String code) {
      //确认验证码有效
        if (StringUtils.isEmpty(code)
        ||StringUtils.isEmpty(user.getPhone())
        ||!code.equals(redisTemplate.opsForValue().get(KEY_PREFIX+user.getPhone()))){
           throw new LyException(400,"验证码或手机号验证失败");
        }
        //2.密码确认

        passwordEncoder.matches("明文密码","加密密码");
        //明文+盐值====》加密，获取到加密密码，拿两次加密密码进行比对
        //根据加密密码推测  盐值
        //加盐加密，盐值
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //保存

        save(user);
    }

    @Override
    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        //查询用户名
        User user=getOne(new QueryWrapper<User>().eq("username",username));
        if (user==null){
            throw new LyException(400,"用户名或者密码错误");
        }
        //检验密码正确性
        if (!passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400,"用户名或者密码错误");
        }
        //转为UserDTO
        return new UserDTO(user);
    }

    @Override
    public void sendCode(String phone) {
//使用Apache的工具类生成6位随机验证码
        String code= RandomStringUtils.randomAlphanumeric(6);
        Map<String,String>msg=new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);
        //发送短信
        amqpTemplate.convertAndSend(msg);
        //存储到redis
        redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);
    }
}